package bancosys.tec.persist.persister;

import org.hibernate.SessionFactory;

import bancosys.tec.persist.Persistable;

/**
 * StatelessPersister implementation that delegates to a stateful persister.
 * 
 * @author lundberg
 */
public class DelegatingStatelessPersister implements StatelessPersister {

    private SessionFactory sessionFactory;

    private PersisterFactory persisterFactory;

    /**
     * Constructor
     * 
     * @param sessionFactory sessionFactory
     * @param persisterFactory persisterFactory
     */
    public DelegatingStatelessPersister(SessionFactory sessionFactory, PersisterFactory persisterFactory) {
        super();
        this.sessionFactory = sessionFactory;
        this.persisterFactory = persisterFactory;
    }

    /**
     * {@inheritDoc}
     */
    public void save(Persistable entity) {
        this.getPersisterFor(entity).save();
    }

    /**
     * {@inheritDoc}
     */
    public void remove(Persistable entity) {
        this.getPersisterFor(entity).remove();
    }

    /**
     * Obtains a stateful persister for the given entity
     * 
     * @param entity entity
     * @return Persister
     */
    private Persister<Persistable> getPersisterFor(Persistable entity) {
        return this.persisterFactory.getPersister(this.sessionFactory, entity);
    }

}
